// (c) 2015 Teresa Holfeld
package com.holfeld.teresa.vocabtrainer;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.holfeld.teresa.vocabtrainer.provider.Vocabulary;

import java.util.List;

/**
 * @author Teresa Holfeld, teresa.holfeld@gmail.com
 */
public class VocabularyArrayAdapter extends ArrayAdapter<Vocabulary> {

    private List<Vocabulary> mVocabularies;
    private Context mContext;

    static class ViewHolder {
        public TextView vocabularyText;
        public TextView vocablesNumber;
        public TextView localesText;
        public Button detailsButton;
    }

    public VocabularyArrayAdapter(Context context, List<Vocabulary> objects) {
        super(context, R.layout.vocabulary_list_item, objects);
        mContext = context;
        mVocabularies = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowView = convertView;
        if (rowView == null) {
            LayoutInflater inflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            rowView = inflater.inflate(R.layout.vocabulary_list_item, parent, false);
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.vocabularyText = (TextView) rowView.findViewById(R.id.vocabularyName);
            viewHolder.vocablesNumber = (TextView) rowView.findViewById(R.id.vocableNumber);
            viewHolder.localesText = (TextView) rowView.findViewById(R.id.vocabularyLocales);
            viewHolder.detailsButton = (Button) rowView.findViewById(R.id.detailsButton);
            rowView.setTag(viewHolder);
        }

        ViewHolder holder = (ViewHolder) rowView.getTag();
        final Vocabulary vocabulary = mVocabularies.get(position);
        String name = vocabulary.getName();
        String number = vocabulary.size() + " words";
        String locale1 = vocabulary.getLocale1();
        String locale2 = vocabulary.getLocale2();
        String locales = locale1 + " - " + locale2;
        holder.vocabularyText.setText(name);
        holder.vocablesNumber.setText(number);
        holder.localesText.setText(locales);
        holder.detailsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                VocabularyListActivity activity = (VocabularyListActivity) mContext;
                activity.goToVocabulary(vocabulary.getName());
            }
        });
        return rowView;
    }

    @Override
    public int getCount() {
        return mVocabularies.size();
    }
}
